<template>
  <div>
    <el-row type="flex" class="row-bg" :gutter="10">

      <el-col :xs="4" :md="4" style="overflow:hidden;">
        <div class="grid-content bg-purple">
          <UploadFile :user="user" :token="token"/>
        </div>
      </el-col>

      <el-col :xs="4" :md="4" style="overflow:hidden;">
        <div class="grid-content bg-purple-light">
          <el-button type="primary" @click="FolderOpen">
            <i class="el-icon-folder-add" style="color: white;"></i>
            <span class="mobileHide">新建文件夹</span>
          </el-button>
        </div>
      </el-col>
      <el-col :xs="10" :md="4" :offset="6" class="search">
        <div class="grid-content bg-purple">
          <Search/>
        </div>
      </el-col>

      <el-col :xs="3" :md="1" style="overflow:hidden;">
        <div class="grid-content bg-purple">
          <el-button icon="el-icon-share" circle
                     @click="$router.push('/getshare')" title="获取分享文件"></el-button>
        </div>
      </el-col>


      <el-col :xs="4" :md="4" style="text-align: left;padding-left: 1%; padding-top: 10px;" class="userMsg">
        <el-dropdown trigger="click" @command="handleCommand">
          <span class="el-dropdown-link">
              <el-avatar :size="45" :src="avatarUrl" :fit="fit" />
            <span class="mobileHide">
              <span>{{ user.userName }}</span>
            </span>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="updateUser">修改信息</el-dropdown-item>
            <el-dropdown-item command="updatepwd">修改密码</el-dropdown-item>
            <el-dropdown-item command="outLogin">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>

      </el-col>

    </el-row>


    <el-dialog
      title="修改密码"
      :visible.sync="dialogVisible"
      class="pwdDialog">
      <span><el-input placeholder="请输入密码" v-model="newPassword" show-password></el-input></span>
      <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="updatePassword">确 定</el-button>
            </span>
    </el-dialog>
    <update-user :user="user" :token="token"/>

  </div>
</template>

<script>
import UploadFile from "./UploadFile";
import Global from "../js/global";
import eventBus from "../js/eventBus";
import Search from "./Search";
import UpdateUser from "./UpdateUser";


export default {
  name: "NavHead",
  props: ['user', 'token'],
  components: {
    'UploadFile': UploadFile,
    'Search': Search,
    'UpdateUser': UpdateUser,
  },
  data() {
    return {
      fit:'cover',
      activeIndex: '0',
      avatarUrl: "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
      dialogVisible: false,
      newPassword: '',
      parentFolderId: '',
    };
  },
  created() {
    eventBus.$on("FolderId", data => {
      this.parentFolderId = data;
    });
    eventBus.$on("loadAvatar", data => {
      if (data === "do") {
        this.loadAvatar();
      }
    });
  },
  methods: {
    handleCommand(command) {
      if (command === "updateUser") {
        eventBus.$emit("userDialog", true);
      } else if (command === "updatepwd") {
        this.dialogVisible = true;
      } else if (command === "outLogin") {
        this.outLogin();
      }
    },
    loadAvatar() {
      const that = this;
      this.getAvatar((rs) => {
        if (rs !== false) {
          that.showAvatar(rs);
        }
      });
    },
    showAvatar(file) {
      let self = this;
      // 看支持不支持FileReader
      if (!file || !window.FileReader) {
        return;
      }
      let reader = new FileReader();
      // 将图片将转成 base64 格式
      reader.readAsDataURL(file);
      // 读取成功后的回调
      reader.onloadend = function () {
        self.avatarUrl = this.result;
      }
    },
    getAvatar(callback) {
      const token = this.$cookies.get("TOKEN");
      if (token === null) {
        this.$router.push({path: '/login'});
      }
      const that = this;
      this.axios({
        url: Global.SERVER_ADDRESS + '/user/get_avatar',
        params: {
          token: token,
        },
        responseType: 'blob',
        method: 'GET',
      }).then(function (resp) {
        let size = resp.data.size
        if (size > 0) {
          //文件浏览
          callback(resp.data);
          console.log("头像加载成功");
        } else {
          //文件浏览
          that.notification(false, "头像加载失败");
        }
      }).catch(function (error) {
        console.log(error)
        that.$message.error(error);
      })
    },
    FolderOpen() {
      const that = this;
      this.$prompt('输入新建文件夹名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({value}) => {
        that.newFolder(value);
      }).catch((msg) => {
        console.log(msg);
      });
    },
    newFolder(newFolderName) {
      const token = this.$cookies.get("TOKEN");
      const that = this;
      this.axios({
        url: Global.SERVER_ADDRESS + '/fileFolder/addFileFolder/' + newFolderName,
        params: {
          token: token,
          parentFolderId: that.parentFolderId
        },
        method: 'POST',
      }).then(function (rs) {
        that.dialogVisible = false;
        if (rs.data.code === '200') {
          that.successNotification("新建文件夹成功");
          eventBus.$emit("refresh", "do");
        } else {
          that.errorNotification("新建文件夹失败！！！")
        }
      }).catch(function (error) {
        console.log(error)
      })
    },
    updatePassword() {
      const token = this.$cookies.get("TOKEN");
      const that = this;
      this.axios({
        url: Global.SERVER_ADDRESS + '/user/updatePassword',
        params: {
          token: token,
          password: that.newPassword
        },
        method: 'PUT',
      }).then(function (rs) {
        that.dialogVisible = false;
        if (rs.data.code === '200') {
          that.successNotification("修改密码成功");

        } else {
          that.errorNotification("修改密码失败！！！")
        }
      }).catch(function (error) {
        console.log(error)
      })
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {
        });
    },
    outLogin() {
      console.log("2")
      this.$cookies.remove("TOKEN")
      this.$router.push('/login');
    },
    handleSelect(key, keyPath) {
    },
    handleRemove(file, fileList) {
    },
    handlePreview(file) {
    },
    successNotification(msg) {
      this.$notify({
        title: '成功',
        message: msg,
        type: 'success'
      });
    },
    open3() {
      this.$notify.info({
        title: '消息',
        message: '这是一条消息的提示消息'
      });
    },
    errorNotification(msg) {
      this.$notify.error({
        title: '失败',
        message: msg
      });
    },
  }
}

</script>

<style scoped>
.userMsg:hover {
  cursor: pointer;
  color: #409EFF;
}

@media only screen and (max-width: 900px) {

  .search {
    margin-left: 0;
  }
}

a {
  text-decoration: none;
}
</style>
